package juc;

/**
 * <pre>类名: InterruptTest</pre>
 * <pre>描述: 中断测试</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/10/30 8:19</pre>
 * <pre>作者: chenwb</pre>
 */
public class InterruptTest {

	private Thread sleepThread;

	/**
	 * @Description 创建一个循环执行的线程
	 * @author chenwb
	 * @date 2020/10/30 9:01
	 */
	synchronized void start() {
		sleepThread = new Thread(() -> {
			// 根据中断标志为判断是否继续执行
			while (!Thread.currentThread().isInterrupted()) {
				System.out.println("sleepThread start!");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					System.out.println("sleepThread has been interrupted");
					// 重置中断标志
					Thread.currentThread().interrupt();
				}
				System.out.println("sleepThread end!");
			}
		});
		sleepThread.start();
	}

	/**
	 * @Description 终止线程的方法stop
	 * @author chenwb
	 * @date 2020/10/30 9:01
	 */
	synchronized void stop() {
		sleepThread.interrupt();
	}


	public static void main(String[] args) throws InterruptedException {
		InterruptTest interruptTest = new InterruptTest();
		// 启动线程
		interruptTest.start();
		// 让线程执行5s
		Thread.sleep(5000);
		// 终止线程
		interruptTest.stop();
	}
}
